package api

import (
	"blog_server/global"
	"blog_server/internal/service"
	"blog_server/pkg"
	"blog_server/pkg/app"
	"github.com/gin-gonic/gin"
)

// GetAuth 获取入参，并根据app_key 和 app_secret查询数据库认证信息是否存在，存在则生成token并返回
func GetAuth(ctx *gin.Context)  {
	param := service.AuthRequest{}
	response := app.NewResponse(ctx)
	err := response.ShouldBind(&param)
	if err != nil {
		global.Logger.Errorf("app.shouldBind err: %v", err)
		errRsp := pkg.InvalidParams.WithDetails(err.Error())
		response.ToErrorResponse(errRsp)
		return
	}
	
	s := service.New()
	err = s.CheckAuth(&param)
	if err != nil {
		global.Logger.Errorf("svc.CheckAuth err: %v", err)
		response.ToErrorResponse(pkg.UnauthorizedAuthNotExist)
		return
	}
	
	token, err := app.GenerateToken(param.AppKey, param.AppSecret)
	if err != nil {
		global.Logger.Errorf("app.GenerateToken err: %v", err)
		response.ToErrorResponse(pkg.UnauthorizedTokenGenerate)
		return
	}
	
	response.ToResponse(gin.H{
		"token": token,
	})
}
